package com.kamistoat.meimeistore.commonsecurity.handler;

import com.kamistoat.meimeistore.commoncore.exception.DemoModeException;
import com.kamistoat.meimeistore.commoncore.exception.InnerAuthException;
import com.kamistoat.meimeistore.commoncore.exception.ServiceException;
import com.kamistoat.meimeistore.commoncore.exception.auth.NotLoginException;
import com.kamistoat.meimeistore.commoncore.exception.auth.NotPermissionException;
import com.kamistoat.meimeistore.commoncore.exception.auth.NotRoleException;
import com.kamistoat.meimeistore.commoncore.utils.StringUtils;
import com.kamistoat.meimeistore.commoncore.web.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器。主要用来处理 NotLoginException NotPermissionException NotRoleException 三种异常。
 * 后来把所有的异常都集中到这个类中
 * 使用@RestControllerAdvice注解标注的类 将作用在所有使用@RequestMapping的控制器的方法上。
 * 因此就能处理任意控制器方法中抛出的异常了
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理 NotLoginException异常
     */
    @ExceptionHandler(NotLoginException.class)
    public AjaxResult handleNotLoginException(NotLoginException notLoginException, HttpServletRequest httpServletRequest) {
        String requestURI = httpServletRequest.getRequestURI();
        LOGGER.error("请求地址'{}', 未登录'{}'", requestURI, notLoginException.getMessage());
        return AjaxResult.error(HttpStatus.FORBIDDEN.value(), "未登录，请先登录");
    }

    /**
     * 处理 NotPermissionException异常
     */
    @ExceptionHandler(NotPermissionException.class)
    public AjaxResult handleNotPermissionException(NotPermissionException notPermissionException, HttpServletRequest httpServletRequest) {
        String requestURI = httpServletRequest.getRequestURI();
        LOGGER.error("请求地址'{}',权限校验失败'{}'", requestURI, notPermissionException.getMessage());
        return AjaxResult.error(HttpStatus.FORBIDDEN.value(), "没有访问权限，请联系管理员授权");
    }

    /**
     * 处理 NotRoleException异常
     */
    @ExceptionHandler(NotRoleException.class)
    public AjaxResult handleNotRoleException(NotRoleException notRoleException, HttpServletRequest httpServletRequest) {
        String requestURI = httpServletRequest.getRequestURI();
        LOGGER.error("请求地址'{}',角色校验失败'{}'", requestURI, notRoleException.getMessage());
        return AjaxResult.error(HttpStatus.FORBIDDEN.value(), "不在权限角色列表中，请联系管理员获取角色");
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException httpRequestMethodNotSupportedException,
                                                          HttpServletRequest httpServletRequest) {
        String requestURI = httpServletRequest.getRequestURI();
        LOGGER.error("请求地址'{}',不支持'{}'请求", requestURI, httpRequestMethodNotSupportedException.getMethod());
        return AjaxResult.error(httpRequestMethodNotSupportedException.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public AjaxResult handleServiceException(ServiceException serviceException, HttpServletRequest httpServletRequest) {
        LOGGER.error(serviceException.getMessage(), serviceException);
        Integer code = serviceException.getCode();
        return StringUtils.isNotNull(code) ? AjaxResult.error(code, serviceException.getMessage()) : AjaxResult.error(serviceException.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult handleRuntimeException(RuntimeException runtimeException, HttpServletRequest httpServletRequest) {
        String requestURI = httpServletRequest.getRequestURI();
        LOGGER.error("请求地址'{}',发生未知异常.", requestURI, runtimeException);
        return AjaxResult.error(runtimeException.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception exception, HttpServletRequest httpServletRequest) {
        String requestURI = httpServletRequest.getRequestURI();
        LOGGER.error("请求地址'{}',发生系统异常.", requestURI, exception);
        return AjaxResult.error(exception.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public AjaxResult handleBindException(BindException bindException) {
        LOGGER.error(bindException.getMessage(), bindException);
        String message = bindException.getAllErrors().get(0).getDefaultMessage();
        return AjaxResult.error(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException methodArgumentNotValidException) {
        LOGGER.error(methodArgumentNotValidException.getMessage(), methodArgumentNotValidException);
        String message = methodArgumentNotValidException.getBindingResult().getFieldError().getDefaultMessage();
        return AjaxResult.error(message);
    }

    /**
     * 内部认证异常
     */
    @ExceptionHandler(InnerAuthException.class)
    public AjaxResult handleInnerAuthException(InnerAuthException innerAuthException) {
        LOGGER.error("内部调用被禁止'{}'", innerAuthException.getMessage());
        return AjaxResult.error(HttpStatus.FORBIDDEN.value(), innerAuthException.getMessage());
    }

    /**
     * 演示模式异常
     */
    @ExceptionHandler(DemoModeException.class)
    public AjaxResult handleDemoModeException(DemoModeException e) {
        return AjaxResult.error("演示模式，不允许操作");
    }
}
